from telnetlib1 import Telnet

floorSwiches={'10':'172.16.100.109','11':'172.16.100.110','12':'172.16.100.111','13':'172.16.100.105','14':'172.16.100.106','15':'172.16.100.107','16':'172.16.100.101','17':'172.16.100.102','18':'172.16.100.103','87':'172.16.100.113','88':'172.16.100.114','89':'172.16.100.115','84':'172.16.100.119','85':'172.16.100.118','86':'172.16.100.117'}

floorNo='1'
ft=None

def connFloor(floor):
    tn=Telnet(floorSwiches.get(floor))
    tn.read_until(b'Password:')
    tn.write(b'Ruijie@123\nen\n')
    tn.read_until(b'Password:')
    tn.write(b'Ruijie@123\n')
    tn.read_until(b'#')
    return tn

def getApInterface(apMac):
    global ft
    if not ft:return False
    ft.write(f'show mac address {apMac}\n'.encode('ascii'))
    data=ft.read_until(b'#').decode('ascii').split('\r\n')[3]
    if data.endswith('#'):
        return False
    else:
        ifNo=data.split()[4]
        return ifNo

with open('roomApMacs.txt') as rd:
    lines=map(lambda x:x.strip().split(),rd.readlines())  #[[apMac,roomNo],...]

with open('apInterfaces.txt','a+') as wr:
    for l in lines:
        no=l[1][0:2]
        if not no==floorNo:
            floorNo=no
            if ft: ft.close()
            ft=connFloor(floorNo)
        ifNo=getApInterface(l[0])
        wr.write(f'{l[1]}\t{ifNo}\n')
    